package com.zf.zfed.audit

import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.zf.zfed.audit.ui.BrightnessSetItem
import com.zf.zfed.audit.ui.BrightnessSlider
import com.zf.zfed.audit.ui.VolumeSetItem
import com.zf.zfed.audit.ui.VolumeSlider

/**
 * 亮度和音量控制测试Activity
 * 用于演示BrightnessSlider、BrightnessSetItem、VolumeSlider和VolumeSetItem的使用
 */
class BrightnessTestActivity : AppCompatActivity() {
    
    private lateinit var volumeItem: VolumeSetItem
    private lateinit var brightnessItem: BrightnessSetItem
    private lateinit var volumeSlider: VolumeSlider
    private lateinit var brightnessSlider: BrightnessSlider
    private lateinit var tvInfo: TextView
    private lateinit var btnRequestPermission: Button
    
    private lateinit var audioManager: AudioManager
    
    private var currentVolume = 50f
    private var currentBrightness = 50f
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_brightness_test)
        
        initViews()
        initAudioManager()
        setupControls()
        checkPermissions()
    }
    
    private fun initViews() {
        volumeItem = findViewById(R.id.volume_item)
        brightnessItem = findViewById(R.id.brightness_item)
        volumeSlider = findViewById(R.id.volume_slider)
        brightnessSlider = findViewById(R.id.brightness_slider)
        tvInfo = findViewById(R.id.tv_info)
        btnRequestPermission = findViewById(R.id.btn_request_permission)
    }
    
    private fun initAudioManager() {
        audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
        
        // 获取当前音量并设置到控件
        val currentVolumeLevel = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        val maxVolumeLevel = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        currentVolume = (currentVolumeLevel.toFloat() / maxVolumeLevel.toFloat()) * 100f
        
        // 获取当前亮度
        try {
            val currentBrightnessLevel = Settings.System.getInt(
                contentResolver,
                Settings.System.SCREEN_BRIGHTNESS,
                128
            )
            currentBrightness = (currentBrightnessLevel.toFloat() / 255f) * 100f
        } catch (e: Exception) {
            currentBrightness = 50f
        }
        
        // 设置初始值
        volumeItem.setVolume(currentVolume)
        brightnessItem.setBrightness(currentBrightness)
        volumeSlider.setProgress(currentVolume)
        brightnessSlider.setProgress(currentBrightness)
        
        updateInfo()
    }
    
    private fun setupControls() {
        // 音量控制设置
        volumeItem.setOnVolumeChangeListener(object : VolumeSlider.OnVolumeChangeListener {
            override fun onVolumeChanged(volume: Float) {
                currentVolume = volume
                setSystemVolume(volume)
                updateInfo()
                volumeSlider.setProgress(volume)
            }
        })
        
        volumeSlider.setOnVolumeChangeListener(object : VolumeSlider.OnVolumeChangeListener {
            override fun onVolumeChanged(volume: Float) {
                currentVolume = volume
                setSystemVolume(volume)
                updateInfo()
                volumeItem.setVolume(volume)
            }
        })
        
        // 亮度控制设置
        brightnessItem.setOnBrightnessChangeListener(object : BrightnessSlider.OnBrightnessChangeListener {
            override fun onBrightnessChanged(brightness: Float) {
                currentBrightness = brightness
                setSystemBrightness(brightness)
                updateInfo()
                brightnessSlider.setProgress(brightness)
            }
        })
        
        brightnessSlider.setOnBrightnessChangeListener(object : BrightnessSlider.OnBrightnessChangeListener {
            override fun onBrightnessChanged(brightness: Float) {
                currentBrightness = brightness
                setSystemBrightness(brightness)
                updateInfo()
                brightnessItem.setBrightness(brightness)
            }
        })
        
        // 权限请求按钮
        btnRequestPermission.setOnClickListener {
            requestWriteSettingsPermission()
        }
    }
    
    private fun setSystemVolume(volume: Float) {
        val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        val systemVolume = ((volume / 100f) * maxVolume).toInt()
        
        audioManager.setStreamVolume(
            AudioManager.STREAM_MUSIC,
            systemVolume,
            0
        )
    }
    
    private fun setSystemBrightness(brightness: Float) {
        if (!Settings.System.canWrite(this)) {
            Toast.makeText(this, "需要系统设置权限才能调节亮度", Toast.LENGTH_SHORT).show()
            return
        }
        
        try {
            val systemBrightness = ((brightness / 100f) * 255f).toInt().coerceIn(1, 255)
            
            // 设置系统亮度
            Settings.System.putInt(
                contentResolver,
                Settings.System.SCREEN_BRIGHTNESS,
                systemBrightness
            )
            
            // 立即应用到当前窗口
            val window = window
            val layoutParams = window.attributes
            layoutParams.screenBrightness = brightness / 100f
            window.attributes = layoutParams
            
        } catch (e: Exception) {
            Toast.makeText(this, "设置亮度失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun updateInfo() {
        val volumePercent = currentVolume.toInt()
        val brightnessPercent = currentBrightness.toInt()
        val systemVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        val maxSystemVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        
        tvInfo.text = "亮度: $brightnessPercent%\n" +
                "音量: $volumePercent%\n" +
                "系统音量: $systemVolume/$maxSystemVolume"
    }
    
    private fun checkPermissions() {
        if (Settings.System.canWrite(this)) {
            btnRequestPermission.text = "已获得系统设置权限"
            btnRequestPermission.isEnabled = false
        } else {
            btnRequestPermission.text = "请求系统设置权限"
            btnRequestPermission.isEnabled = true
        }
    }
    
    private fun requestWriteSettingsPermission() {
        if (!Settings.System.canWrite(this)) {
            val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
            intent.data = Uri.parse("package:$packageName")
            startActivity(intent)
        }
    }
    
    override fun onResume() {
        super.onResume()
        checkPermissions()
    }
}